package org.zkoss.zktc.console;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.zkoss.zktc.core.groovy.Snippet;

public class SnippetLoader {

	public List<Snippet> loadSnippets() {
		return loadSnippets("example1");
	}
	
	public List<Snippet> loadSnippets(String name) {
		URL url = getClass().getResource(name + ".groovy");// _ to running in
															// eclipse
		if (url == null) {
			throw new RuntimeException("groovy file not found of " + name);
		}
		InputStream is = null;
		BufferedReader r = null;
		
		ArrayList<Snippet> snippets = new ArrayList<Snippet>();
		try {
			r = new BufferedReader(new InputStreamReader(is = url.openStream(),
					"UTF8"));
			String l;
			while ((l = r.readLine()) != null) {
				l = l.trim();
				if("".equals(l) || l.startsWith("//")) continue;
				snippets.add(new Snippet(l));
			}
		} catch (Exception e) {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e1) {
				}
			}
			throw new RuntimeException(e.getMessage(), e);
		}

		return snippets;
	}
}
